package co.yixiang.modules.tools.rest;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.api.YshopException;
import co.yixiang.constant.ShopConstants;
import co.yixiang.constant.SystemConfigConstants;
import co.yixiang.enums.ShopCommonEnum;
import co.yixiang.modules.tools.service.dto.LocalStorageDto;
import co.yixiang.modules.tools.service.LocalStorageService;
import co.yixiang.oss.config.OssProperties;
import co.yixiang.oss.service.OssTemplate;
import co.yixiang.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "上传统一管理")
@RestController
@RequestMapping("/api/upload")
@Slf4j
@SuppressWarnings("unchecked")
public class UploadController {

    private final LocalStorageService localStorageService;
    private final RedisUtils redisUtils;
    private final OssProperties ossProperties;
    private final OssTemplate ossTemplate;

    public UploadController(LocalStorageService localStorageService, RedisUtils redisUtils,
                            OssProperties ossProperties, OssTemplate ossTemplate) {
        this.localStorageService = localStorageService;
        this.redisUtils = redisUtils;
        this.ossProperties = ossProperties;
        this.ossTemplate = ossTemplate;
    }


    @ApiOperation("上传文件")
    @PostMapping
        /**
     * 文件上传接口
     * @param name 文件名称
     * @param type 文件类型
     * @param files 上传的文件数组
     * @return 上传结果
     */
    public ResponseEntity<Object> create(@RequestParam(defaultValue = "") String name,
                                         @RequestParam(defaultValue = "") String type,
                                         @RequestParam("file") MultipartFile[] files) {

        // 获取后台API地址
        String localUrl = redisUtils.getY(ShopConstants.ADMIN_API_URL);
        // 如果类型为空，使用移动端API地址
        if(StrUtil.isBlank(type)){
            localUrl = redisUtils.getY(SystemConfigConstants.API_URL) + "/api";
        }
        // 获取文件存储模式
        String mode = redisUtils.getY(SystemConfigConstants.FILE_STORE_MODE);
        StringBuilder url = new StringBuilder();

        // 模式1：本地存储
        if (ShopCommonEnum.STORE_MODE_1.getValue().toString().equals(mode)) {
            if(StrUtil.isBlank(localUrl)){
                throw new YshopException("本地上传,请先登陆系统配置后台/移动端API地址");
            }
            // 遍历处理每个上传的文件
            for (MultipartFile file : files) {
                // 创建本地存储记录
                LocalStorageDto localStorageDTO = localStorageService.create(name, file);
                // 构建文件访问URL
                if ("".equals(url.toString())) {
                    url = url.append(localUrl + "/file/" + localStorageDTO.getType() + "/" + localStorageDTO.getRealName());
                } else {
                    url = url.append(","+localUrl + "/file/" + localStorageDTO.getType() + "/" + localStorageDTO.getRealName());
                }
            }
        } else {
            // 模式2：OSS对象存储
            for (MultipartFile file : files) {
                // 生成唯一的文件名
                String [] originalFilename = file.getOriginalFilename().split("\\.");
                String fileName = ossProperties.getBucketName()+"/file/"+originalFilename[0] + "-" + 
                                IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
                try {
                    // 上传文件到OSS
                    ossTemplate.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 构建OSS文件访问URL
                url = url.append(ossProperties.getCustomDomain()+"/"+fileName);
                /*String fileUrl = String.format(ossProperties.getCustomDomain(), fileName);
                if ("".equals(url.toString())) {
                    url = url.append(fileUrl);
                }else{
                    url = url.append(","+fileUrl);
                }*/
            }
        }

        // 构建返回结果
        Map<String, Object> map = new HashMap<>(2);
        map.put("errno", 0);  // 0表示上传成功
        map.put("link", url); // 返回文件访问链接
        return new ResponseEntity(map, HttpStatus.CREATED);
    }


}
